#include <iostream>
#include "common.h"

using namespace std;

int main()
{
    // 服务端创建共享内存
    key_t key = getKey();
    int shmid = createShm(key, gsize);

    cout << "getpid(): " << getpid() << endl;
    cout << "server key: " << toHEX(key) << endl;

    char *start = (char*)shmat(shmid, NULL, 0); //去关联
    if ((void*)start == (void*)-1)
    {
        cerr << "shmat fail!"
             << "errno: " << errno << " | " << strerror(errno) << endl;
        shmctl(shmid, IPC_RMID, NULL);  //即使异常了，也要把共享内存释放
        exit(1);
    }

    struct shmid_ds buf;
    int n = shmctl(shmid, IPC_STAT, &buf);
    if (n == -1)
    {
        cerr << "shmctl fail!"
             << "errno: " << errno << " | " << strerror(errno) << endl;
        shmctl(shmid, IPC_RMID, NULL);  //即使异常了，也要把共享内存释放
        exit(1);
    }

    cout << "==================" << endl;
    cout << "buf.shm_cpid: " << buf.shm_cpid << endl;
    cout << "buf.shm_perm.__key: " << toHEX(buf.shm_perm.__key) << endl;


    shmdt(start);   //去关联
    shmctl(shmid, IPC_RMID, NULL);
    return 0;
}